package wechat

import (
	"baokaobang/conf"
	"bytes"
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
)

type MiniSceneQrcode struct {
	Scene string `json:"scene"`
	Page  string `json:"page"`
	Width int    `json:"width"`
}

type MiniSceneQrcodeRes struct {
	Errcode     int    `json:"errcode"`
	Errmsg      string `json:"errmsg"`
	ContentType string `json:"contentType"`
}

func CreateMiniSceneQrcode(scene, page, imgName string, width int) (string, error) {
	var err error

	var accessToken string
	accessToken, err = GetMiniAccessToken()
	if err != nil {
		return "", err
	}

	var content []byte
	miniSceneQrcode := MiniSceneQrcode{
		Scene: scene,
		Page:  page,
		Width: width,
	}
	content, err = json.Marshal(miniSceneQrcode)
	if err != nil {
		return "", err
	}

	var resp *http.Response
	var body []byte
	url := fmt.Sprintf("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s", accessToken)
	req, _ := http.NewRequest("POST", url, strings.NewReader(string(content)))
	req.Header.Set("Content-Type", "application/json")
	tr := &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	client := &http.Client{Transport: tr}
	resp, err = client.Do(req)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	dir := fmt.Sprintf("%s/mini_qrcode", conf.UploadPrefix.Front)
	_, err = os.Stat(dir)
	if err != nil {
		err = os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			return "", err
		}
	}

	var qrcode *os.File
	name := fmt.Sprintf("%s/%s", dir, imgName)
	qrcode, err = os.Create(name)
	defer qrcode.Close()
	_, err = io.Copy(qrcode, bytes.NewReader(body))
	if err != nil {
		return "", err
	}

	return fmt.Sprintf("/mini_qrcode/%s", imgName), nil
}
